package com.nine.system.service.impl;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nine.common.entity.*;
import com.nine.common.entity.engineerVO.EngineerAddress;
import com.nine.common.tool.AliyunOss;
import com.nine.common.tool.ResponseResult;
import com.nine.common.tool.SnowflakeIdGenerator;
import com.nine.system.mapper.*;
import com.nine.system.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import com.nine.common.tool.AliyunOss;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @Description:
 * @ClassName: OrderServiceImpl
 * @Author: luodeng
 * @Date: 2023/6/5 16:55
 * @Version: 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper mapper;

    @Autowired
    private OrderRollbackMapper Rmapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private EngineerMapper engineerMapper;

    @Autowired
    private AliyunOss aliyunOss;

    @Autowired
    private OrderRollbackMapper orderRollbackMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private MoneyMapper moneyMapper;

    @Override
    public ResponseResult addOrder(String productType,
                                   String orderDescription,
                                   int orderPriority,
                                   String orderClientname,
                                   String orderClientphone,
                                   String orderProvince,
                                   String orderCity,
                                   String orderArea,
                                   String orderAddress,
                                   Date orderDate,
                                   int orderTime) {
        /*订单创建  利用雪花算法生成orderId
            更新状态日志
        * */
        OrderForm order = new OrderForm();
        String urls = null;
        int number = 1;
        SnowflakeIdGenerator generator = new SnowflakeIdGenerator(1,1);
        Long id = generator.generateId();
        order.setUserId(StpUtil.getLoginIdAsLong());
        order.setOrderId(id);
        order.setProductType(productType);
        order.setOrderDescription(orderDescription);
        order.setOrderPriority(orderPriority);
        order.setOrderClientname(orderClientname);
        order.setOrderClientphone(orderClientphone);
        order.setOrderProvince(orderProvince);
        order.setOrderCity(orderCity);
        order.setOrderArea(orderArea);
        order.setOrderAddress(orderAddress);
        order.setOrderDate(orderDate);
        order.setOrderTime(orderTime);


        int insert = mapper.insert(order);

        if(insert==0){
            return ResponseResult.fail("订单提交失败，请稍后再试");
        }else{

            LogForm newLog = new LogForm();
            newLog.setOrderId(order.getOrderId());
            newLog.setLogStatus(0);
            newLog.setLogTime(LocalDateTime.now());
            newLog.setLogDescription("订单创建完成");

            logMapper.insert(newLog);
        }
        return ResponseResult.ok("您的订单已提交");
    }


    @Override
    public ResponseResult<List<LogForm>> getStatus(Long orderId) {
        LambdaQueryWrapper<LogForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LogForm::getOrderId,orderId);
        List<LogForm> logForms = logMapper.selectList(wrapper);
        return ResponseResult.ok(logForms);
    }

    //
    private List<OrderFormVO101> ConvertIdToName(List<OrderForm> originList){
        List<OrderFormVO101> list = new ArrayList<>();

        for (int i=0;i<originList.size();i++){


            OrderForm orderForm = originList.get(i);

            Long userId = orderForm.getUserId();
            LambdaQueryWrapper<UserForm> userwrapper = new LambdaQueryWrapper<>();
            userwrapper.eq(UserForm::getUserId,userId);
            UserForm userForm = userMapper.selectOne(userwrapper);
            String userName = userForm.getUserName();

            Long engineerId = orderForm.getEngineerId();
            LambdaQueryWrapper<EngineerForm> engwrapper = new LambdaQueryWrapper<>();
            engwrapper.eq(EngineerForm::getEngineerId,engineerId);

            String engineerName="未接单";
            if(engineerId != 0){
                EngineerForm engineerForm = engineerMapper.selectOne(engwrapper);
                engineerName = engineerForm.getEngineerName();
            }

            OrderFormVO101 orderFormVO101 = new OrderFormVO101(orderForm, userName, engineerName);
            list.add(orderFormVO101);
        }
        return list;
    }
//平台查看所有订单
    @Override
    public ResponseResult<List<OrderFormVO101>> getAll(int page,int limit) {
        IPage<OrderForm> iPage= new Page<>(page,limit);
        IPage<OrderForm> iPage1 = mapper.selectPage(iPage, null);
        List<OrderForm> records = iPage1.getRecords();

        List<OrderFormVO101> list = ConvertIdToName(records);

        long count = iPage1.getTotal();
        return ResponseResult.okc(list,count);
    }

    @Override
    public ResponseResult<List<OrderFormVO101>> findSome(int orderStatus,int orderPriority,String orderDate,int orderTime,String orderId,String orderClientphone,int page,int limit){

        IPage<OrderForm> iPage= new Page<>(page,limit);
        LambdaQueryWrapper<OrderForm> orderwrapper = new LambdaQueryWrapper<>();

        if(orderStatus!=-1)
            orderwrapper.eq(OrderForm::getOrderStatus,orderStatus);

        if(orderPriority!=-1)
            orderwrapper.eq(OrderForm::getOrderPriority,orderPriority);

        if(orderDate != null && !orderDate.isEmpty()){
            java.sql.Date date = java.sql.Date.valueOf(orderDate);
            orderwrapper.eq(OrderForm::getOrderDate,date);
        }

        if(orderTime!=-1)
            orderwrapper.eq(OrderForm::getOrderTime,orderTime);

        if(orderId!= null && !orderId.isEmpty()){
            long id = Long.parseLong(orderId);
            orderwrapper.eq(OrderForm::getOrderId,id);
        }

        if(orderClientphone!= null && !orderClientphone.isEmpty()){
            orderwrapper.eq(OrderForm::getOrderClientphone,orderClientphone);
        }

        IPage<OrderForm> iPage1 = mapper.selectPage(iPage, orderwrapper);
        List<OrderForm> records = iPage1.getRecords();

        List<OrderFormVO101> list = ConvertIdToName(records);


        long count = iPage1.getTotal();
        return ResponseResult.okc(list,count);
    }

    public ResponseResult getLogs(long orderId,int page, int limit){
        IPage<LogForm> iPage= new Page<>(page,limit);
        LambdaQueryWrapper<LogForm> logwrapper = new LambdaQueryWrapper<>();

        logwrapper.eq(LogForm::getOrderId,orderId);

        //根据时间升序
        logwrapper.orderByAsc(LogForm::getLogTime);

        IPage<LogForm> iPage1 = logMapper.selectPage(iPage, logwrapper);
        List<LogForm> records = iPage1.getRecords();

        List<LogFormVO> list = new ArrayList<>();
        for (int i=0;i<records.size();i++){

            LogForm logForm = records.get(i);

            Long engineerId = logForm.getEngineerId();
            LambdaQueryWrapper<EngineerForm> engwrapper = new LambdaQueryWrapper<>();
            engwrapper.eq(EngineerForm::getEngineerId,engineerId);

            String engineerName="-";
            if(engineerId != null && engineerId != 0){
                EngineerForm engineerForm = engineerMapper.selectOne(engwrapper);
                engineerName = engineerForm.getEngineerName();
            }

            LogFormVO logFormVO = new LogFormVO(logForm, engineerName);
            list.add(logFormVO);
        }

        long count = iPage1.getTotal();
        return ResponseResult.okc(list,count);
    }
    @Override
    public ResponseResult<List<OrderFormVO101>> findByOrderId(String orderId, int page, int limit) {
        IPage<OrderForm> iPage= new Page<>(page,limit);
        LambdaQueryWrapper<OrderForm> orderwrapper = new LambdaQueryWrapper<>();
        if(orderId != null && !orderId.isEmpty()){
            long id = Long.parseLong(orderId);
            orderwrapper.eq(OrderForm::getOrderId,id);
        }

        IPage<OrderForm> iPage1 = mapper.selectPage(iPage, orderwrapper);
        List<OrderForm> records = iPage1.getRecords();

        List<OrderFormVO101> list = ConvertIdToName(records);

        long count = iPage1.getTotal();
        return ResponseResult.okc(list,count);
    }


    @Override
    public ResponseResult getNo() {
        LambdaQueryWrapper<OrderForm> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(OrderForm::getEngineerId,0);

        List<OrderForm> orderForms = mapper.selectList(wrapper);

        return ResponseResult.ok(orderForms);
    }

    private boolean isEngineerOrderTaken(long engineerId, int orderTime, Date orderDate) {
        // 根据工程师ID和订单时间查询已接单的订单
        LambdaQueryWrapper<OrderForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderForm::getEngineerId, engineerId)
                .eq(OrderForm::getOrderTime, orderTime)
                .eq(OrderForm::getOrderDate, orderDate)
                .eq(OrderForm::getOrderStatus, 1);
        List<OrderForm> takenOrders = mapper.selectList(wrapper);

        // 如果存在已接单的订单，则返回 true，否则返回 false
        return !takenOrders.isEmpty();
    }

    @Override
    public ResponseResult takeOrder(long orderId) {


        //获取当前工程师的 engineerId
        Long engineerId = StpUtil.getLoginIdAsLong();

        System.out.println("当前的工程师ID："+engineerId);
        //匹配 数据库order_form的orderId 并获取
        LambdaQueryWrapper<OrderForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderForm::getOrderId,orderId);
        OrderForm orderForm = mapper.selectOne(wrapper);
        System.out.println("当前的接手的order:"+orderForm);
        // 判断订单是否已被接单
        int orderTime = orderForm.getOrderTime();//获取订单时间
        Date orderDate = orderForm.getOrderDate();
        if (orderForm.getOrderStatus() == 1) {
            return ResponseResult.fail("order is used");
        }
        else if(isEngineerOrderTaken(engineerId, orderTime, orderDate)){
            System.out.println("当前时段已经接单");
            return ResponseResult.fail("order time is taken");
        }
        else{
            //将该订单的工程师id设置为 刚刚查到的 并把订单状态设置为 1 代表已被接单的意思
            orderForm.setEngineerId(engineerId);
            orderForm.setOrderStatus(1);

            //创建log表
            LogForm logForm = new LogForm();
            //设置log表的基本信息
            logForm.setLogTime(LocalDateTime.now());
            logForm.setLogStatus(1); //1代表接单
            logForm.setLogDescription("工程师已接手该订单");
            logForm.setOrderId(orderId);
            logForm.setEngineerId(engineerId);

            //调用mapper层 更新到数据库中
            mapper.updateById(orderForm);
            logMapper.insert(logForm);

            return ResponseResult.ok("ok");
        }

    }



    public ResponseResult searchOrders(String orderProvince, String orderCity, String orderArea, int orderTime, int page, int limit) {
        LambdaQueryWrapper<OrderForm> wrapper = new LambdaQueryWrapper<>();

        // 添加条件搜索
        wrapper.eq(OrderForm::getOrderProvince, orderProvince)
                .eq(OrderForm::getOrderCity, orderCity)
                .eq(OrderForm::getOrderArea, orderArea)
                .eq(OrderForm::getOrderTime, orderTime)
                .eq(OrderForm::getOrderStatus, 0);

        IPage<OrderForm> iPage = new Page<>(page, limit);
        IPage<OrderForm> iPage1 = mapper.selectPage(iPage, wrapper);
        List<OrderForm> records = iPage1.getRecords();
        long count = iPage1.getTotal();

        if (orderTime == -1 && orderArea.length() >= 1) { // 只选择了地区不选择时间搜索
            wrapper.clear(); // 清除之前的查询条件
            wrapper.eq(OrderForm::getOrderProvince, orderProvince)
                    .eq(OrderForm::getOrderArea, orderArea)
                    .eq(OrderForm::getOrderCity, orderCity)
                    .eq(OrderForm::getOrderStatus, 0);

            iPage1 = mapper.selectPage(iPage, wrapper);
            records = iPage1.getRecords();
            count = iPage1.getTotal();
        } else if (orderArea.length() <= 1 && orderTime != -1) { // 只选择了时间不选择地区搜索
            wrapper.clear(); // 清除之前的查询条件
            wrapper.eq(OrderForm::getOrderProvince, orderProvince)
                    .eq(OrderForm::getOrderTime, orderTime)
                    .eq(OrderForm::getOrderCity, orderCity)
                    .eq(OrderForm::getOrderStatus, 0);

            iPage1 = mapper.selectPage(iPage, wrapper);
            records = iPage1.getRecords();
            count = iPage1.getTotal();
        } else if (records.isEmpty() && orderArea.length() <= 1 && orderTime == -1) { // 地区和时间都不选择的搜索
            wrapper.clear(); // 清除之前的查询条件
            wrapper.eq(OrderForm::getOrderProvince, orderProvince)
                    .eq(OrderForm::getOrderCity, orderCity)
                    .eq(OrderForm::getOrderStatus, 0);

            iPage1 = mapper.selectPage(iPage, wrapper);
            records = iPage1.getRecords();
            count = iPage1.getTotal();
        }

        List<OrderFormVO101> list = ConvertIdToName(records);
        return ResponseResult.okc(list, count);
    }



    @Override
    public ResponseResult<OrderFormVO102> findData() {

        int uid = StpUtil.getLoginIdAsInt();
        LambdaQueryWrapper<OrderForm> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(OrderForm::getUserId,uid);

        ResponseResult responseResult = new ResponseResult(0,"");

        responseResult.setCount(mapper.selectCount(wrapper1));

        List<OrderForm> orderFormList = mapper.selectList(wrapper1);
        List<OrderFormVO102> orderFormVO102List = new ArrayList<>();

        for (OrderForm orderForm : orderFormList) {
            OrderFormVO102 orderFormVO102 = new OrderFormVO102();
            BeanUtils.copyProperties(orderForm,orderFormVO102);

            LambdaQueryWrapper<EngineerForm> wrapper = new LambdaQueryWrapper<>();

            wrapper.eq(EngineerForm::getEngineerId,orderForm.getEngineerId());
            EngineerForm engineerForm = engineerMapper.selectOne(wrapper);
            if(engineerForm != null){
                orderFormVO102.setEngineerName(engineerForm.getEngineerName());
                orderFormVO102.setEngineerPhone(engineerForm.getEngineerPhone());
            }

            orderFormVO102List.add(orderFormVO102);
        }

        responseResult.setData(orderFormVO102List);

        return responseResult;
    }


    @Override
    public ResponseResult<OrderFormVO102> searchData(int orderStatus,int orderPriority,String orderDate,int orderTime,String orderClientphone){

        int uid = StpUtil.getLoginIdAsInt();

        LambdaQueryWrapper<OrderForm> orderwrapper = new LambdaQueryWrapper<>();

        orderwrapper.eq(OrderForm::getUserId,uid);

        if(orderStatus!=-1)
            orderwrapper.eq(OrderForm::getOrderStatus,orderStatus);

        if(orderPriority!=-1)
            orderwrapper.eq(OrderForm::getOrderPriority,orderPriority);

        if(orderDate != null && !orderDate.isEmpty()){
            java.sql.Date date = java.sql.Date.valueOf(orderDate);
            orderwrapper.eq(OrderForm::getOrderDate,date);
        }

        if(orderTime!=-1)
            orderwrapper.eq(OrderForm::getOrderTime,orderTime);

        if(orderClientphone!= null && !orderClientphone.isEmpty()){
            orderwrapper.eq(OrderForm::getOrderClientphone,orderClientphone);
        }

        ResponseResult responseResult = new ResponseResult(0,"");

        responseResult.setCount(mapper.selectCount(orderwrapper));

        List<OrderForm> orderFormList = mapper.selectList(orderwrapper);

        List<OrderFormVO102> orderFormVO102List = new ArrayList<>();

        for (OrderForm orderForm : orderFormList) {
            OrderFormVO102 orderFormVO102 = new OrderFormVO102();
            BeanUtils.copyProperties(orderForm,orderFormVO102);

            LambdaQueryWrapper<EngineerForm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EngineerForm::getEngineerId,orderForm.getEngineerId());
            EngineerForm engineerForm = engineerMapper.selectOne(wrapper);
            if(engineerForm != null){
                orderFormVO102.setEngineerName(engineerForm.getEngineerName());
            }
            orderFormVO102List.add(orderFormVO102);
        }

        responseResult.setData(orderFormVO102List);

        return responseResult;

    }





    //默认查看当前工程师地区的未接单的订单
    @Override
    public ResponseResult getOrdersBy103() {
        long uid = StpUtil.getLoginIdAsLong();
        System.out.println(uid);
        EngineerAddress engineerAddress = engineerMapper.getEngineerAddress(uid);
        LambdaQueryWrapper<OrderForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderForm::getOrderProvince, engineerAddress.getEngineerProvince())
                .eq(OrderForm::getOrderCity, engineerAddress.getEngineerCity())
                .eq(OrderForm::getOrderArea, engineerAddress.getEngineerArea())
                .and(i -> i.eq(OrderForm::getOrderStatus, 0)
                        );

        /*
        wrapper.eq(OrderForm::getOrderProvince,
                engineerAddress.getEngineerProvince()).eq(OrderForm::getOrderCity,
                engineerAddress.getEngineerCity()).eq(OrderForm::getOrderArea,
                engineerAddress.getEngineerArea()).eq(OrderForm::getOrderStatus,0);
*/
        List<OrderForm> orderForms = mapper.selectList(wrapper);
        List<OrderFormVO101> list = ConvertIdToName(orderForms);
        return ResponseResult.okc(list,1);
    }

    //查看工程师当前接
    @Override
    public ResponseResult getOrdersNowEngineer() {
        Long engineerId = StpUtil.getLoginIdAsLong();
        LambdaQueryWrapper<OrderForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderForm::getEngineerId, engineerId)
                .eq(OrderForm::getOrderStatus, 1);
        List<OrderForm> takenOrders = mapper.selectList(wrapper);
        List<OrderFormVO101> list = ConvertIdToName(takenOrders);
        return ResponseResult.okc(list,1);
    }

    @Override
    public ResponseResult getOrdersFinishedEngineer() {
        Long engineerId = StpUtil.getLoginIdAsLong();
        LambdaQueryWrapper<OrderForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderForm::getEngineerId, engineerId);
        List<OrderForm> takenOrders = mapper.selectList(wrapper);
        List<OrderFormVO101> list = ConvertIdToName(takenOrders);
        return ResponseResult.okc(list,1);
    }


    @Override
    public ResponseResult uploadVerify(
            Long orderId,
            MultipartFile orderVerify
    ) {
        //验证当前登录用户是否为该订单负责人
        long uid = StpUtil.getLoginIdAsLong();
        OrderForm orderForm1 = mapper.selectById(orderId);

        if(orderForm1.getEngineerId()!=uid){
            return ResponseResult.fail("身份信息错误");
        }

        String fileName = orderVerify.getOriginalFilename();
        String fileExtension = null;
        File file = null;
        try {
            file = File.createTempFile("temp", null);
            FileCopyUtils.copy(orderVerify.getBytes(), file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        if (fileName != null) {
            int dotIndex = fileName.lastIndexOf(".");
            if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
                fileExtension = fileName.substring(dotIndex);
            }
        }
        fileName = orderId+"_Verify"+fileExtension;


        orderForm1.setOrderVerify(fileName);
        orderForm1.setOrderStatus(2);
        orderForm1.setQuartzTime(LocalDateTime.now());//提交时间记录
        //创建log表
        LogForm logForm = new LogForm();
        //设置log表的基本信息
        logForm.setLogTime(LocalDateTime.now());
        logForm.setLogStatus(2); //2代表待确定
        logForm.setLogDescription("工程师已完成工作并提交工单 等待商家审核");
        logForm.setOrderId(orderId);
        logForm.setEngineerId(uid);

        //TODO 使用阿里云oss文件储存服务 fileName需要格式化 弄成字母或者数字.文件类型
        aliyunOss.handleUploadOrder(file,fileName,Long.toString(orderId));
        mapper.updateById(orderForm1);
        logMapper.insert(logForm);
        return ResponseResult.ok("上传成功");
    }

    //这是 商家 对工程师已经拍照完结后的单子进行审核的接口
    @Override
    public ResponseResult getOrdersCheckBy102() {
        int uid = StpUtil.getLoginIdAsInt();
        LambdaQueryWrapper<OrderForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderForm::getOrderStatus,2);
        wrapper.eq(OrderForm::getUserId,uid);
        List<OrderForm> orderForms = mapper.selectList(wrapper);
        List<OrderFormVO101> orderFormVO101s = ConvertIdToName(orderForms);
        return ResponseResult.ok(orderFormVO101s);
    }

    //商家端审核  使商家来审核 工程师的
    @Override
    public ResponseResult orderFinished(long orderId,int orderCheck){
        //订单是否有问题
        //1 没问题

        if(orderCheck == 1){
            //订单状态设为 3
            OrderForm orderForm = mapper.selectById(orderId);
            orderForm.setOrderStatus(3);

            LogForm logForm = new LogForm();
            logForm.setEngineerId(orderForm.getEngineerId());
            logForm.setLogTime(LocalDateTime.now());
            logForm.setLogDescription("经过商家审核，该订单正常完结");
            logForm.setLogStatus(3);
            logForm.setOrderId(orderId);
            mapper.updateById(orderForm);
            logMapper.insert(logForm);

            //扣款逻辑
            int orderPriority = orderForm.getOrderPriority();
            //底价50元，每增加一级优先级加20元，优先级默认为0
            BigDecimal money=BigDecimal.valueOf(50+orderPriority* 20L);

            //商家扣钱

            //读取订单对应的商家
            UserInfo userInfo = userInfoMapper.selectById(orderForm.getUserId());
            //减去这单的钱
            userInfo.setBalance(userInfo.getBalance().subtract(money));
            //更新余额
            userInfoMapper.updateById(userInfo);
            //日志
            MoneyLogForm moneyLogForm = new MoneyLogForm();
            moneyLogForm.setOrderId(orderForm.getOrderId());
            moneyLogForm.setLogTime(LocalDateTime.now());
            moneyLogForm.setSysId(orderForm.getUserId());
            moneyLogForm.setMoney(money.negate());//负数
            moneyLogForm.setLogDescription("手动确认订单扣款");
            moneyMapper.insert(moneyLogForm);

            //平台抽成10%，工程师进账90%
            BigDecimal amoney=money.multiply(new BigDecimal("0.1"));
            BigDecimal engmoney=money.multiply(new BigDecimal("0.9"));

            //平台加钱 默认sysid为1是平台账号
            userInfo = userInfoMapper.selectById(1);

            userInfo.setBalance(userInfo.getBalance().add(amoney));

            userInfoMapper.updateById(userInfo);

            MoneyLogForm moneyLogForm2 = new MoneyLogForm();
            moneyLogForm2.setOrderId(orderForm.getOrderId());
            moneyLogForm2.setLogTime(LocalDateTime.now());
            moneyLogForm2.setSysId(1L);
            moneyLogForm2.setMoney(amoney);
            moneyLogForm2.setLogDescription("完成订单抽成");
            moneyMapper.insert(moneyLogForm2);

            //工程师加钱
            userInfo = userInfoMapper.selectById(orderForm.getEngineerId());

            userInfo.setBalance(userInfo.getBalance().add(engmoney));

            userInfoMapper.updateById(userInfo);

            MoneyLogForm moneyLogForm3 = new MoneyLogForm();
            moneyLogForm3.setOrderId(orderForm.getOrderId());
            moneyLogForm3.setLogTime(LocalDateTime.now());
            moneyLogForm3.setSysId(orderForm.getEngineerId());
            moneyLogForm3.setMoney(engmoney);
            moneyLogForm3.setLogDescription("完成订单收入");
            moneyMapper.insert(moneyLogForm3);

//            //日志更新
//            LogForm logForm2 = new LogForm();
//            logForm2.setEngineerId(orderForm.getEngineerId());
//            logForm2.setLogTime(LocalDateTime.now());
//            logForm2.setLogDescription("完成支付，扣款"+money+"元，工程师进账"+engmoney+"元，平台抽成"+amoney+"元");
//            logForm2.setLogStatus(3);
//            logForm2.setOrderId(orderId);
//            logMapper.insert(logForm2);

            return  ResponseResult.ok("订单结束成功");
        }
        //2 有问题
        else if(orderCheck == 2){
            OrderForm orderForm = mapper.selectById(orderId);
            orderForm.setOrderStatus(4);

            LogForm logForm = new LogForm();
            logForm.setEngineerId(orderForm.getEngineerId());
            logForm.setLogTime(LocalDateTime.now());
            logForm.setLogDescription("经过商家审核 该订单存在问题 移交平台管理审核");
            logForm.setLogStatus(4);
            logForm.setOrderId(orderId);
            mapper.updateById(orderForm);
            logMapper.insert(logForm);


            return  ResponseResult.ok("订单未完结");
        }
        else{
            //系统1分钟自动确认
            OrderForm orderForm = mapper.selectById(orderId);
            orderForm.setOrderStatus(3);

            LogForm logForm = new LogForm();
            logForm.setEngineerId(orderForm.getEngineerId());
            logForm.setLogTime(LocalDateTime.now());
            logForm.setLogDescription("商家未在规定时间内审核，平台自动完结该订单");
            logForm.setLogStatus(3);
            logForm.setOrderId(orderId);
            mapper.updateById(orderForm);
            logMapper.insert(logForm);

            //扣款逻辑
            int orderPriority = orderForm.getOrderPriority();
            //底价50元，每增加一级优先级加20元，优先级默认为0
            BigDecimal money=BigDecimal.valueOf(50+orderPriority* 20L);

            //商家扣钱

            //读取订单对应的商家
            UserInfo userInfo = userInfoMapper.selectById(orderForm.getUserId());
            //减去这单的钱
            userInfo.setBalance(userInfo.getBalance().subtract(money));
            //更新余额
            userInfoMapper.updateById(userInfo);
            //日志
            MoneyLogForm moneyLogForm = new MoneyLogForm();
            moneyLogForm.setOrderId(orderForm.getOrderId());
            moneyLogForm.setLogTime(LocalDateTime.now());
            moneyLogForm.setSysId(orderForm.getUserId());
            moneyLogForm.setMoney(money.negate());//负数
            moneyLogForm.setLogDescription("手动确认订单扣款");
            moneyMapper.insert(moneyLogForm);

            //平台抽成10%，工程师进账90%
            BigDecimal amoney=money.multiply(new BigDecimal("0.1"));
            BigDecimal engmoney=money.multiply(new BigDecimal("0.9"));

            //平台加钱 默认sysid为1是平台账号
            userInfo = userInfoMapper.selectById(1);

            userInfo.setBalance(userInfo.getBalance().add(amoney));

            userInfoMapper.updateById(userInfo);

            MoneyLogForm moneyLogForm2 = new MoneyLogForm();
            moneyLogForm2.setOrderId(orderForm.getOrderId());
            moneyLogForm2.setLogTime(LocalDateTime.now());
            moneyLogForm2.setSysId(1L);
            moneyLogForm2.setMoney(amoney);
            moneyLogForm2.setLogDescription("完成订单抽成");
            moneyMapper.insert(moneyLogForm2);

            //工程师加钱
            userInfo = userInfoMapper.selectById(orderForm.getEngineerId());

            userInfo.setBalance(userInfo.getBalance().add(engmoney));

            userInfoMapper.updateById(userInfo);

            MoneyLogForm moneyLogForm3 = new MoneyLogForm();
            moneyLogForm3.setOrderId(orderForm.getOrderId());
            moneyLogForm3.setLogTime(LocalDateTime.now());
            moneyLogForm3.setSysId(orderForm.getEngineerId());
            moneyLogForm3.setMoney(engmoney);
            moneyLogForm3.setLogDescription("完成订单收入");
            moneyMapper.insert(moneyLogForm3);

//            //日志更新
//            LogForm logForm2 = new LogForm();
//            logForm2.setEngineerId(orderForm.getEngineerId());
//            logForm2.setLogTime(LocalDateTime.now());
//            logForm2.setLogDescription("完成支付，扣款"+money+"元，工程师进账"+engmoney+"元，平台抽成"+amoney+"元");
//            logForm2.setLogStatus(3);
//            logForm2.setOrderId(orderId);
//            logMapper.insert(logForm2);

            return  ResponseResult.ok("订单结束成功");
        }

    }

    @Override
    public ResponseResult getOrderCheckBy101() {
        LambdaQueryWrapper<OrderForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderForm::getOrderStatus,4);

        List<OrderForm> orderForms = mapper.selectList(wrapper);
        List<OrderFormVO101> orderFormVO101s = ConvertIdToName(orderForms);
        return ResponseResult.ok(orderFormVO101s);
    }

    @Override
    public ResponseResult<OrderCount> getOrderCount(long engineerId) {
        OrderCount orderCount = orderMapper.getOrderCount(engineerId);
        return ResponseResult.ok(orderCount);
    }

    @Override
    public ResponseResult returnOrder(long orderId, String reason) {
        long engineerId = StpUtil.getLoginIdAsLong();
        OrderRollbackForm orderRollbackForm = new OrderRollbackForm();
        orderRollbackForm.setEngineerId(engineerId);
        orderRollbackForm.setOrderId(orderId);
        orderRollbackForm.setReason(reason);

        orderRollbackMapper.insert(orderRollbackForm);
        LogForm logForm = new LogForm();
        logForm.setOrderId(orderId);
        logForm.setLogTime(LocalDateTime.now());
        logForm.setEngineerId(engineerId);
        logForm.setLogDescription("工程师申请退单");
        logForm.setLogStatus(1);
        logMapper.insert(logForm);
        return ResponseResult.ok("发起退单申请成功");
    }

    @Override
    public ResponseResult getOrderFormByRollbackId(int status, int page, int limit) {
        LambdaQueryWrapper<OrderRollbackForm> wrapper = new LambdaQueryWrapper<>();
        IPage<OrderRollbackForm> iPage1=null;

        if(status == 4){
            IPage<OrderRollbackForm> iPage = new Page<>(page, limit);
            iPage1 = orderRollbackMapper.selectPage(iPage, null);
        }else{
            wrapper.eq(OrderRollbackForm::getStatus,status);
            IPage<OrderRollbackForm> iPage = new Page<>(page, limit);
            iPage1 = orderRollbackMapper.selectPage(iPage, wrapper);
        }


        List<OrderRollbackForm> records = iPage1.getRecords();
        long total = iPage1.getTotal();


        ArrayList<RollbackFormVO> list = new ArrayList<>();

        for (int i = 0; i < records.size(); i++){
            OrderRollbackForm orderRollbackForm = records.get(i);
            Long orderId = orderRollbackForm.getOrderId();


            OrderForm orderForm = orderMapper.selectById(orderId);


            ArrayList<OrderForm> orderForms = new ArrayList<>();
            orderForms.add(orderForm);

            List<OrderFormVO101> orderFormVO101s = ConvertIdToName(orderForms);
            OrderFormVO101 orderFormVO101 = orderFormVO101s.get(0);

            RollbackFormVO rollbackFormVO = new RollbackFormVO(orderRollbackForm);
            rollbackFormVO.setOrderFormVO101(orderFormVO101);
            list.add(rollbackFormVO);

        }

        return ResponseResult.okc(list, total);
    }

        @Override
        public ResponseResult changeRollbackStatus(Long rollbackId, int status) {
            LambdaQueryWrapper<OrderRollbackForm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderRollbackForm::getRollbackId, rollbackId);
            OrderRollbackForm orderRollbackForm = Rmapper.selectOne(wrapper);
            orderRollbackForm.setStatus(status);
            Long orderId = orderRollbackForm.getOrderId();
            Rmapper.updateById(orderRollbackForm);
            if(status == 1){
                OrderForm orderForm = new OrderForm();
                orderForm.setEngineerId(0L);
                orderForm.setOrderStatus(0);
                LambdaUpdateWrapper<OrderForm> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(OrderForm::getOrderId, orderId);
                mapper.update(orderForm, updateWrapper);
                LogForm logForm = new LogForm();
                logForm.setOrderId(orderId);
                logForm.setLogTime(LocalDateTime.now());
                logForm.setLogDescription("工程师退单申请通过！");
                logForm.setLogStatus(1);
                logMapper.insert(logForm);
            }
            else if(status == 2){
                LogForm logForm = new LogForm();
                logForm.setOrderId(orderId);
                logForm.setLogTime(LocalDateTime.now());
                logForm.setLogDescription("工程师退单申请未通过！");
                logForm.setLogStatus(1);
                logMapper.insert(logForm);
            }
            return ResponseResult.ok("ok");
        }

        //平台审核 商家拒绝的订单  最终审判
    @Override
    public ResponseResult orderCheckBy101(long orderId, int orderCheck) {
        if(orderCheck == 1){
            //如果 check 为 1 代表有问题 该订单回到订单池
            //
            OrderForm orderForm = mapper.selectById(orderId);
            orderForm.setOrderStatus(0);

            LogForm logForm = new LogForm();
            logForm.setEngineerId(orderForm.getEngineerId());
            logForm.setLogTime(LocalDateTime.now());
            logForm.setLogDescription("经过平台最终裁决 该订单存在问题 已被退回订单池");
            logForm.setLogStatus(0);
            logForm.setOrderId(orderId);
            mapper.updateById(orderForm);
            logMapper.insert(logForm);



            return  ResponseResult.ok("订单未完结");
        }
        //2 没有问题
        else{
            OrderForm orderForm = mapper.selectById(orderId);
            orderForm.setOrderStatus(3);

            LogForm logForm = new LogForm();
            logForm.setEngineerId(orderForm.getEngineerId());
            logForm.setLogTime(LocalDateTime.now());
            logForm.setLogDescription("经过平台最终裁决 该订单没有问题 已正常完结");
            logForm.setLogStatus(3);
            logForm.setOrderId(orderId);
            mapper.updateById(orderForm);
            logMapper.insert(logForm);

            //扣款逻辑
            int orderPriority = orderForm.getOrderPriority();
            //底价50元，每增加一级优先级加20元，优先级默认为0
            BigDecimal money=BigDecimal.valueOf(50+orderPriority* 20L);

            //商家扣钱

            //读取订单对应的商家
            UserInfo userInfo = userInfoMapper.selectById(orderForm.getUserId());
            //减去这单的钱
            userInfo.setBalance(userInfo.getBalance().subtract(money));
            //更新余额
            userInfoMapper.updateById(userInfo);
            //日志
            MoneyLogForm moneyLogForm = new MoneyLogForm();
            moneyLogForm.setOrderId(orderForm.getOrderId());
            moneyLogForm.setLogTime(LocalDateTime.now());
            moneyLogForm.setSysId(orderForm.getUserId());
            moneyLogForm.setMoney(money.negate());//负数
            moneyLogForm.setLogDescription("手动确认订单扣款");
            moneyMapper.insert(moneyLogForm);

            //平台抽成10%，工程师进账90%
            BigDecimal amoney=money.multiply(new BigDecimal("0.1"));
            BigDecimal engmoney=money.multiply(new BigDecimal("0.9"));

            //平台加钱 默认sysid为1是平台账号
            userInfo = userInfoMapper.selectById(1);

            userInfo.setBalance(userInfo.getBalance().add(amoney));

            userInfoMapper.updateById(userInfo);

            MoneyLogForm moneyLogForm2 = new MoneyLogForm();
            moneyLogForm2.setOrderId(orderForm.getOrderId());
            moneyLogForm2.setLogTime(LocalDateTime.now());
            moneyLogForm2.setSysId(1L);
            moneyLogForm2.setMoney(amoney);
            moneyLogForm2.setLogDescription("完成订单抽成");
            moneyMapper.insert(moneyLogForm2);

            //工程师加钱
            userInfo = userInfoMapper.selectById(orderForm.getEngineerId());

            userInfo.setBalance(userInfo.getBalance().add(engmoney));

            userInfoMapper.updateById(userInfo);

            MoneyLogForm moneyLogForm3 = new MoneyLogForm();
            moneyLogForm3.setOrderId(orderForm.getOrderId());
            moneyLogForm3.setLogTime(LocalDateTime.now());
            moneyLogForm3.setSysId(orderForm.getEngineerId());
            moneyLogForm3.setMoney(engmoney);
            moneyLogForm3.setLogDescription("完成订单收入");
            moneyMapper.insert(moneyLogForm3);

//            //日志更新
//            LogForm logForm2 = new LogForm();
//            logForm2.setEngineerId(orderForm.getEngineerId());
//            logForm2.setLogTime(LocalDateTime.now());
//            logForm2.setLogDescription("完成支付，扣款"+money+"元，工程师进账"+engmoney+"元，平台抽成"+amoney+"元");
//            logForm2.setLogStatus(3);
//            logForm2.setOrderId(orderId);
//            logMapper.insert(logForm2);

            return  ResponseResult.ok("订单结束成功");
        }
    }
    @Override
    public ResponseResult getStatus4OrderCount() { //平台管理员查看状态为4（异议订单等待裁决）的订单
        int status4OrderCount = orderMapper.getStatus4OrderCount();
        return ResponseResult.ok(status4OrderCount);
    }

    @Override
    public ResponseResult<OrderRollbackCount> getOrderRollbackCount() { //平台管理员查看退回订单数量
        OrderRollbackCount orderRollbackCount = orderRollbackMapper.getOrderRollbackCount();
        return ResponseResult.ok(orderRollbackCount);
    }

    @Override
    public ResponseResult getStatusCountBy102() {
        long uid = StpUtil.getLoginIdAsLong();
        OrderCount statusCountBy102 = orderMapper.getStatusCountBy102(uid);

        return ResponseResult.ok(statusCountBy102);
    }

    @Override
    public ResponseResult getStatus2CountBy102() {
        long uid = StpUtil.getLoginIdAsLong();
        int status2 = orderMapper.getStatus2CountBy102(uid);
        return ResponseResult.ok(status2);
    }
}
